package com.test.list.imageLoading;

/** Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
import android.widget.ImageView;

import com.test.list.R;
import com.test.list.interfaces.Viewable;
import com.test.list.simple.Utils;

public class ImageLoader
{
	final int stub_id = R.drawable.stub;
	static ExecutorService mExecutorService;
	public static final int THUMBNAIL_SIZE = 128;
	private static final int THREAD_POOL_SIZE = 5;// 10;//5
	public static final String TAG = "ImageLoader";
	private MemoryCache mMemoryCache = new MemoryCache();
	private FileCache mFileCache;
	private Map<ImageView, String> mImageViews = Collections
			.synchronizedMap(new WeakHashMap<ImageView, String>());

	public ImageLoader(Context context)
	{
		mFileCache = new FileCache(context);
		if (mExecutorService == null)
		{
			mExecutorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
		}
	}

	public void DisplayImage(Viewable viewable, ImageView imageView)
	{
		mImageViews.put(imageView, viewable.getMainPictureID());
		Bitmap bitmap = mMemoryCache.get(viewable.getMainPictureID());
		if (bitmap != null)
			imageView.setImageBitmap(bitmap);
		else
		{
			// queuePhoto(viewable.getMainPictureID(), imageView);
			queuePhoto(viewable, imageView);
			imageView.setImageResource(stub_id);

		}
	}

	private void queuePhoto(Viewable viewable, ImageView imageView)
	{
		PhotoToLoad p = new PhotoToLoad(viewable, imageView);
		mExecutorService.submit(new PhotosLoader(p));
	}

	private Bitmap getBitmapFromFile(String url)
	{
		File f = mFileCache.getFile(url);

		// from SD cache
		Bitmap retVal = ImageUtils.decodeFile(f);
		if (retVal == null)
		{

			// from web
			try
			{

				URL imageUrl = new URL(url);
				HttpURLConnection conn = (HttpURLConnection) imageUrl
						.openConnection();
				conn.setConnectTimeout(30000);
				conn.setReadTimeout(30000);
				conn.setInstanceFollowRedirects(true);
				InputStream is = conn.getInputStream();
				OutputStream os = new FileOutputStream(f);
				Utils.CopyStream(is, os);
				os.close();
				retVal = ImageUtils.decodeFile(f);
				// return bitmap;
			} catch (Exception ex)
			{
				ex.printStackTrace();
			}
		}

		return retVal;
	}

	private class PhotoToLoad
	{

		public String url;
		public ImageView imageView;

		public Viewable mView;

		public PhotoToLoad(Viewable v, ImageView i)
		{
			mView = v;
			url = mView.getMainPictureID();
			imageView = i;
		}

		// public Uri uri;
		// public PhotoToLoad(String u, ImageView i)
		// {
		// url = u;
		// if (u != null)
		// {
		// uri = ContactMngr.getInstance().getContactPhotoUri(
		// Long.valueOf(u));
		// }
		// imageView = i;
		// }

	}

	class PhotosLoader implements Runnable
	{
		PhotoToLoad photoToLoad;

		PhotosLoader(PhotoToLoad photoToLoad)
		{
			this.photoToLoad = photoToLoad;
		}

		@Override
		public void run()
		{
			if (imageViewReused(photoToLoad))
				return;

			Bitmap bmp = photoToLoad.mView.getBitmap();
			mMemoryCache.put(photoToLoad.url, bmp);

			if (imageViewReused(photoToLoad))
				return;
			BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
			try
			{
				Activity a = (Activity) photoToLoad.imageView.getContext();
				a.runOnUiThread(bd);
			} catch (Exception e)
			{
				Log.e(TAG, e.getMessage());
			}
		}
	}

	boolean imageViewReused(PhotoToLoad photoToLoad)
	{
		String tag = mImageViews.get(photoToLoad.imageView);
		if (tag == null || !tag.equals(photoToLoad.url))
			return true;
		return false;
	}

	// Used to display bitmap in the UI thread
	class BitmapDisplayer implements Runnable
	{
		Bitmap bitmap;
		PhotoToLoad photoToLoad;

		public BitmapDisplayer(Bitmap b, PhotoToLoad p)
		{
			bitmap = b;
			photoToLoad = p;
		}

		public void run()
		{
			if (imageViewReused(photoToLoad))
				return;
			if (bitmap != null)
				photoToLoad.imageView.setImageBitmap(bitmap);
			else
				photoToLoad.imageView.setImageResource(stub_id);
		}
	}

	public void clearCache()
	{
		mMemoryCache.clear();
		mFileCache.clear();
	}

}
